<template>
  <n-input
    v-model:value="localValue"
    :type="type"
    :placeholder="placeholder"
    :disabled="disabled || loading"
    :clearable="clearable"
    :loading="loading"
    v-bind="$attrs"
    @update:value="handleUpdate"
    @clear="handleClear"
  >
    <template #prefix>
      <slot name="prefix">
        <!-- 使用默认内容 -->
        <span v-if="prefix">{{ prefix }}</span>
      </slot>
    </template>
    <template #suffix>
      <slot name="suffix">
        <!-- 使用默认内容 -->
        <span v-if="suffix">{{ suffix }}</span>
      </slot>
    </template>
  </n-input>
</template>

<script setup>
import { ref, watch } from 'vue'

const props = defineProps({
  modelValue: {
    type: [String, Number],
    default: ''
  },
  type: {
    type: String,
    default: 'text'
  },
  placeholder: {
    type: String,
    default: ''
  },
  disabled: Boolean,
  loading: Boolean,
  clearable: {
    type: Boolean,
    default: true
  },
  // 将prefix和suffix改为any类型，以便接受字符串或组件
  prefix: [String, Object],
  suffix: [String, Object]
})

const emit = defineEmits(['update:modelValue', 'clear'])

const localValue = ref(props.modelValue)

watch(() => props.modelValue, (newValue) => {
  localValue.value = newValue
})

const handleUpdate = (value) => {
  localValue.value = value
  emit('update:modelValue', value)
}

const handleClear = () => {
  localValue.value = ''
  emit('update:modelValue', '')
  emit('clear')
}
</script>